//
//  GPSOSContactListController.m
//  Keping
//
//  Created by 23 on 2017/12/9.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "GPSOSContactListController.h"
#import "GPSOSContactListCell.h"
#import "KSOSRequest.h"
#import "GPChatController.h"


@interface GPSOSContactListController () <UITableViewDelegate,UITableViewDataSource, UITextFieldDelegate>

/**
 tableview
 */
@property(nonatomic,weak)UITableView*tableView;
/**
 头部搜索栏
 */
@property(nonatomic,weak)UIView*headerView;
/**
 搜索
 */
@property(nonatomic,weak)UITextField * searchView;

/**
 数据源
 */
@property(nonatomic,strong)NSMutableArray*dataAry;

/**记录发送的第几个联系人*/
@property(nonatomic,assign) NSInteger count;

@end

@implementation GPSOSContactListController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    
    self.count = 0;
    
    [self loadData];
}

-(void)setUI
{
    self.navigationItem.title=@"Select your friends";
    
    //头部搜索栏
    UIView*headerView=[[UIView alloc]init];
    [self.view addSubview:headerView];
    self.headerView=headerView;
    
    UITextField * searchView = [[UITextField alloc]init];
    searchView.textAlignment=NSTextAlignmentCenter;
    searchView.backgroundColor=[UIColor colorWithHexString:@"#6d52fb"];
    searchView.layer.masksToBounds=YES;
    searchView.delegate = self;
    searchView.textColor=[UIColor whiteColor];
    searchView.returnKeyType = UIReturnKeySearch;
    searchView.enablesReturnKeyAutomatically = YES;
    [searchView addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:UIControlEventEditingChanged];
    [headerView addSubview:searchView];
    searchView.placeholder=@"Search";
    self.searchView=searchView;
    
    
    UITableView*tableView=[[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.delegate=self;
    tableView.dataSource=self;
    [self.view addSubview:tableView];
    tableView.tableFooterView=[UIView new];
    self.tableView=tableView;
}
-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.headerView.frame=CGRectMake(0, 0, self.view.width, K_FactorH(65));
    
    CGFloat H= K_FactorH(45);
    self.searchView.frame=CGRectMake(K_FactorW(25),(self.headerView.height-H)/2, self.headerView.width-2*K_FactorW(25), H);
    self.searchView.layer.cornerRadius=self.searchView.height/2;
    
    
    self.tableView.frame=CGRectMake(0, CGRectGetMaxY(self.headerView.frame), self.view.width, self.view.height-CGRectGetMaxY(self.headerView.frame));
}
#pragma mark -- UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataAry.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GPSOSContactListCell *cell=[GPSOSContactListCell cellWithTableView:tableView];
    cell.listModel = self.dataAry[indexPath.row];
    
    return cell;;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return K_FactorH(75);
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WEAKSELF
    
    //取出模型
    KSosListModel *model = self.dataAry[indexPath.row];
    
//    if ((self.isTest == NO) && self.count) {
//        self.isTest = YES;
//    }
    
    NSString *message = self.isTest?@"SOS Test":@"SOS";
    UIAlertController *ac = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    [ac addAction:[UIAlertAction actionWithTitle:@"Send" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
//        weakSelf.count++;
        
        //快速发送求救信息
        GPChatViewModel *chatViewModel =  [[GPChatViewModel alloc] initWithChatType:EMChatTypeChat conversationId:model.phone toId:model.phone toNickName:model.nickName toAvatarURLPath:[KGetImageURL stringByAppendingPathComponent:model.profile]];
        
        // 掉接口给对方推送通知
        NSString *type = weakSelf.isTest?@"test":@"snap";
        [weakSelf push:model type:type];
        
        if (weakSelf.isTest) {
            //测试SOS
            [chatViewModel sendSOSLocationMessage:@"SOS test" latitude:self.latitude longitude:self.longitude];
            return;
        }
        
//        if (weakSelf.locationString.length) {
//            NSString *sosMsg = [NSString stringWithFormat:@"SOS:%@", weakSelf.locationString];
//            [chatViewModel sendSOSTestMessage:sosMsg];
//            return;
//        }
        
        //发送SOS图片位置等紧急消息
        [chatViewModel sendSOSMessage:self.image latitude:self.latitude longitude:self.longitude address:@""];
//        发送图片SOS
//        [chatViewModel sendImageMessage:self.image];
        
        
    }]];
    
    [self presentViewController:ac animated:YES completion:nil];
    
}

- (void)push:(KSosListModel *)model type:(NSString *)type {
    [self showLoading];
    KSOSRequest* loginRequest = [[KSOSRequest alloc] initWithURL:kPushURL];
    loginRequest.isPost = NO;
    
    loginRequest.params = @{@"partyId":model.friendId, @"type":type};
    //    loginRequest.params = @{@"partyId":model.Id, @"type":type};
    [loginRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        [self hideHUD];
        
        NSDictionary *response = request.responseJSONObject;
        if ([response[@"statusCode"] integerValue] != 200) {
            
            [self showErrorText:response[@"msg"] errCode:[response[@"statusCode"] integerValue]];
            return;
        }
        
        
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [self hideHUD];
        [self showError:request.error];
    }];
}


#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSString *key = textField.text;
    
    //发起搜索请求
    [self showLoading];
//    KSOSRequest *searchRequest =  [[KSOSRequest alloc] initWithURL:kSosSearchFriendsURL];
//    searchRequest.params = @{@"searchContent":key};
//    [searchRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
//        
//        [self hideHUD];
//        NSDictionary *response = request.responseJSONObject;
//        if ([response[@"statusCode"] integerValue] != 200) {
//            
//            [self showErrorText:response[@"msg"] errCode:[response[@"statusCode"] integerValue]];
//            return;
//        }
//        
//        NSMutableArray *arrayM = [NSMutableArray array];
//        for (NSDictionary *dict in response[@"relationFriendViews"]) {
//            KSosListModel *model = [KSosListModel modelWithDictionary:dict];
//            [arrayM addObject:model];
//        }
//        
//        self.dataAry = [NSMutableArray arrayWithArray:arrayM];
//        [self.tableView reloadData];
//        
//        NSLog(@"----->Smallyou:%@", response);
//        
//    } failure:^(__kindof KBaseRequest * _Nonnull request) {
//        [self hideHUD];
//        [self showError:request.error];
//    }];
    
    
    return YES;
}

- (void)textFieldValueChanged:(UITextField *)textField
{
    NSString *key = textField.text;
    if (key.length == 0) {
        //获取数据
        [self loadData];
    }
}



- (void)loadData
{
    [self showLoading];
    KSOSRequest* loginRequest = [[KSOSRequest alloc] initWithURL:kSosListURL];
    [loginRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        [self hideHUD];
        
        NSDictionary *response = request.responseJSONObject;
        if ([response[@"statusCode"] integerValue] != 200) {
            
            [self showErrorText:response[@"msg"] errCode:[response[@"statusCode"] integerValue]];
            return;
        }
        
        
        NSMutableArray *arrayM = [NSMutableArray array];
        for (NSDictionary *dict in response[@"relationFriendViews"]) {
            KSosListModel *model = [KSosListModel modelWithDictionary:dict];
            [arrayM addObject:model];
        }
        
        self.dataAry = [NSMutableArray arrayWithArray:arrayM];
        [self.tableView reloadData];
        
        
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [self hideHUD];
        [self showError:request.error];
    }];
}


@end
